package core

import (
	"context"
	"encoding/json"
	"ez/apps/core/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type GateWay struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64      `json:"id" bson:"id,omitempty"`
	Ip          string     `json:"ip" bson:"ip"`             //IP地址
	Port        int64      `json:"port" bson:"port"`         //端口
	IsOn        bool       `json:"isOn" bson:"isOn"`         //开启
	Hosts       []*Host    `json:"hosts" bson:"hosts"`       //主机
	HostsIds    []int64    `json:"hostsIds" bson:"hostsIds"` //主机
	CreateAt    time.Time  `json:"createAt" bson:"createAt"`
	UpdateAt    time.Time  `json:"updateAt" bson:"updateAt"`
	DeleteAt    *time.Time `json:"deleteAt" bson:"deleteAt"`
}

func (this *GateWay) DocName() string { return "GateWay" }
func (this *GateWay) GetId() int64    { return this.Id }
func (this *GateWay) SetId(id int64)  { this.Id = id }
func (this *GateWay) Create() error {
	return this.GetFactory().Create(this)
}
func (this *GateWay) Replace() error {
	return this.GetFactory().Replace(this)
}
func (this *GateWay) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *GateWay) Delete() error {
	return this.GetFactory().Delete(this)
}
func (this *GateWay) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *GateWay) Destroy() error {
	return this.GetFactory().Destroy(this)
}
func (this *GateWay) ToString() string {
	return string(this.ToBytes())
}
func (this *GateWay) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *GateWay) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *GateWay) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}
func (this *GateWay) LoadHosts() {
	if this.Hosts == nil {
		this.Hosts = make([]*Host, 0)
	}
	if this.HostsIds == nil {
		this.HostsIds = make([]int64, 0)
	}
	if len(this.HostsIds) > 0 {
		this.Hosts = make([]*Host, 0)
		for _, v := range this.HostsIds {
			find, e := NewHostCrud().FindId(v)
			if e == nil {
				this.Hosts = append(this.Hosts, find)
			}
		}
	}
}
func (this *GateWay) ClearRelationsBeforeSave() mgo.Doc {
	this.Hosts = nil
	return this
}
func neverUsed_GateWay() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type GateWayAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *GateWay
	Session *ez.Session
}

func NewGateWayAccessControl(model *GateWay, action string, session *ez.Session) *GateWayAccessControl {
	ctrl := &GateWayAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.GateWayAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
